<template>
  <div class="page-wrap">
    <div class="page-header">
      <div class="page-title">
        报表汇总
        <el-tag type="info" effect="plain" class="title-tag">Inventory Report</el-tag>
        <el-tag 
          :type="connectionStatus === 'Connected' ? 'success' : connectionStatus === 'Connecting' ? 'warning' : 'danger'" 
          effect="plain" 
          class="status-tag"
        >
          {{ connectionStatus === 'Connected' ? '实时连接' : connectionStatus === 'Connecting' ? '连接中' : '连接断开' }}
        </el-tag>
      </div>
      <div class="page-actions">
        <el-button @click="handleReset" :loading="loading" plain>重置</el-button>
        <el-button type="primary" @click="fetchList" :loading="loading">刷新</el-button>
        <el-button type="success" @click="exportCsv" :disabled="!tableData.length">导出 CSV</el-button>
      </div>
    </div>

    <el-card class="search-card" shadow="never">
      <el-form :inline="true" label-width="90px" @submit.prevent>
        <el-form-item label="产品名称">
          <el-input
            v-model="query.ProductName"
            placeholder="模糊搜索 产品名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleSearch"
            @input="handleProductNameChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-alert
      v-if="lastUpdateTime"
      :title="`数据已实时更新 - ${lastUpdateTime}`"
      type="success"
      :closable="false"
      show-icon
      class="update-alert"
    />

    <el-alert
      v-if="connectionStatus === 'Disconnected'"
      title="实时连接已断开，正在尝试重新连接..."
      type="warning"
      :closable="false"
      show-icon
      class="connection-alert"
    />

    <el-alert
      v-if="connectionError"
      :title="connectionError"
      type="error"
      :closable="true"
      show-icon
      class="error-alert"
      @close="connectionError = ''"
    />

    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">记录数</div>
        <div class="stat-value">{{ total }}</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">本页入库合计</div>
        <div class="stat-value">{{ formatNumber(sumIn) }}</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">本页出库合计</div>
        <div class="stat-value">{{ formatNumber(sumOut) }}</div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <div class="stat-title">本页结存合计</div>
        <div class="stat-value">{{ formatNumber(sumBalance) }}</div>
      </el-card>
    </div>

    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" border stripe height="520" :header-cell-style="{background:'#f7f9fc'}">
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="productNumber" label="产品编号" min-width="120" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouseName" label="仓库" min-width="120" />
        <el-table-column prop="unitPrice" label="单价" width="100" align="right">
          <template #default="{ row }">{{ formatNumber(row.unitPrice) }}</template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="inQuantity" label="入库数" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.inQuantity) }}</template>
        </el-table-column>
        <el-table-column prop="outQuantity" label="出库数" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.outQuantity) }}</template>
        </el-table-column>
        <el-table-column prop="balanceQuantity" label="结存数" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.balanceQuantity) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" text @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="query.pageindex"
          :page-size="query.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>

  <el-dialog v-model="detailVisible" title="明细" width="560px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="产品名称">{{ detailRow?.productName }}</el-descriptions-item>
      <el-descriptions-item label="产品编号">{{ detailRow?.productNumber }}</el-descriptions-item>
      <el-descriptions-item label="规格型号">{{ detailRow?.specification }}</el-descriptions-item>
      <el-descriptions-item label="单位">{{ detailRow?.unit }}</el-descriptions-item>
      <el-descriptions-item label="仓库">{{ detailRow?.warehouseName }}</el-descriptions-item>
      <el-descriptions-item label="单价">{{ formatNumber(detailRow?.unitPrice || 0) }}</el-descriptions-item>
      <el-descriptions-item label="申请人">{{ detailRow?.applicant }}</el-descriptions-item>
      <el-descriptions-item label="入库数">{{ formatNumber(detailRow?.inQuantity || 0) }}</el-descriptions-item>
      <el-descriptions-item label="出库数">{{ formatNumber(detailRow?.outQuantity || 0) }}</el-descriptions-item>
      <el-descriptions-item label="结存数">{{ formatNumber(detailRow?.balanceQuantity || 0) }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible=false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import * as signalR from '@microsoft/signalr'
import { ReadClients } from '../../Urls/AxiosHelper'

const Read = ReadClients[0]
interface SupplierItem {
  productName: string
  productNumber: string
  specification: string
  unit: string
  warehouseName: string
  unitPrice: number
  applicant: string
  inQuantity: number
  outQuantity: number
  balanceQuantity: number
}

interface ApiResponse<T> {
  code: number
  message: string
  data: {
    totalCount: number
    totalPage: number
    data: T[]
  }
}

const loading = ref(false)
const tableData = ref<SupplierItem[]>([])
const total = ref(0)
const connectionStatus = ref<'Disconnected' | 'Connecting' | 'Connected'>('Disconnected')
const lastUpdateTime = ref('')
const connection = ref<signalR.HubConnection | null>(null)
const connectionError = ref('')
const currentEndpoint = ref('')

const query = reactive({
  ProductName: '',
  pageindex: 1,
  pagesize: 10,
})
// 🔧 优化：动态获取后端API地址
const getBackendBaseUrl = () => {
  console.log('后端 API 地址: 使用 ReadClients 配置')
  return '' // 使用 ReadClients 时不需要基础URL
}

// 🔧 优化：动态获取SignalR端点
const getSignalREndpoints = () => {
  // 使用代理路径构建SignalR端点
  const endpoints = [
    '/api2/api/chathub',        // 标准API路径（推荐）
    '/api2/chathub'              // 简化路径
  ]
  
  console.log('SignalR端点列表:', endpoints)
  return endpoints
}
// 🔧 修复：智能连接 SignalR - 适配Konga网关
async function initSignalR() {
  const endpoints = getSignalREndpoints()
  let lastError: Error | null = null
  
  for (const endpoint of endpoints) {
    try {
      console.log('尝试连接 SignalR:', endpoint)
      connectionStatus.value = 'Connecting'
      connectionError.value = ''
      
      // 清理之前的连接
      if (connection.value) {
        await connection.value.stop()
        connection.value = null
      }

      connection.value = new signalR.HubConnectionBuilder()
        .withUrl(endpoint, {
          skipNegotiation: false, // 🔧 重要：不跳过协商
          transport: signalR.HttpTransportType.WebSockets | 
                     signalR.HttpTransportType.LongPolling | 
                     signalR.HttpTransportType.ServerSentEvents,
          // 🔧 新增：CORS相关配置
          withCredentials: true,  // 允许携带凭证
        })
        .withAutomaticReconnect([0, 2000, 10000, 30000]) // 🔧 增强：自动重连策略
        .configureLogging(signalR.LogLevel.Information) // 🔧 增强：详细日志
        .build()

      // 🔧 增强：连接事件处理
      connection.value.onclose((error) => {
        console.error('SignalR 连接关闭:', error)
        connectionStatus.value = 'Disconnected'
        ElMessage.warning('实时连接已断开，正在尝试重连...')
      })

      connection.value.onreconnecting((error) => {
        console.log('SignalR 重新连接中:', error)
        connectionStatus.value = 'Connecting'
        ElMessage.info('正在重新连接...')
      })

      connection.value.onreconnected((connectionId) => {
        console.log('SignalR 重新连接成功:', connectionId)
        connectionStatus.value = 'Connected'
        ElMessage.success('实时连接已恢复')
        // 重新连接后，带上当前条件进行一次刷新
        sendRealTimeQuery()
      })

      // 🔧 修复：接收后端广播的数据
      connection.value.on('SendMessage', (data: ApiResponse<SupplierItem>) => {
        console.log('收到实时数据更新:', data)
        // 直接更新表格数据，不进行条件判断
        updateTableDataDirectly(data)
        lastUpdateTime.value = new Date().toLocaleTimeString()
      })

      // 🔧 增强：连接启动
      await connection.value.start()
      connectionStatus.value = 'Connected'
      currentEndpoint.value = endpoint
      ElMessage.success(`实时连接已建立: ${endpoint}`)
      
      // 首次建立连接后，按当前条件发一次查询
      await sendRealTimeQuery()
      
      // 连接成功，跳出循环
      return
      
    } catch (error) {
      console.error(`连接失败 ${endpoint}:`, error)
      lastError = error as Error
      
      // 清理失败的连接
      if (connection.value) {
        try {
          await connection.value.stop()
        } catch (e) {
          console.error('清理连接失败:', e)
        }
        connection.value = null
      }
      
      // 继续尝试下一个端点
      continue
    }
  }
  
  // 所有端点都连接失败
  connectionStatus.value = 'Disconnected'
  const errorMessage = lastError ? `所有端点连接失败: ${lastError.message}` : '所有端点连接失败'
  connectionError.value = errorMessage
  ElMessage.error(errorMessage)
}

// 🔧 修复：直接更新表格数据
function updateTableDataDirectly(data: ApiResponse<SupplierItem>) {
  if (data.code === 200 && data.data) {
    console.log('直接更新表格数据，总记录数:', data.data.totalCount)
    // 直接使用后端返回的数据，不进行前端过滤
    tableData.value = data.data.data || []
    total.value = data.data.totalCount || 0
    
    // 显示更新提示
    ElMessage.success('数据已实时更新')
  }
}


// 🔧 修复：发送实时查询
async function sendRealTimeQuery() {
  if (connection.value && connectionStatus.value === 'Connected') {
    try {
      // 发送查询条件到后端
      await connection.value.invoke('SendMessage', '用户', query.ProductName || '')
      console.log('已发送实时查询请求')
    } catch (e) {
      console.error('发送实时查询失败:', e)
      ElMessage.error('发送实时查询失败')
    }
  }
}

// 🔧 修复：防抖处理产品名称变化
function handleProductNameChange() {
  if (connectionStatus.value === 'Connected') {
    clearTimeout((window as any).productNameTimeout)
    ;(window as any).productNameTimeout = setTimeout(() => {
      sendRealTimeQuery()
    }, 500)
  }
}


// 🔧 修复：获取列表数据
async function fetchList() {
  loading.value = true
  try {
    const params: any = {
      pageindex: query.pageindex,
      pagesize: query.pagesize
    }
    
    if (query.ProductName) params.ProductName = query.ProductName

    console.log('发送的查询参数:', params)

    const res = await Read.get<ApiResponse<SupplierItem>>('/wareread/api/ReportSummary/Supplierlist', { params })
    const payload = res.data
    
    if (payload.code !== 200) {
      throw new Error(payload.message || '请求失败')
    }
    
    tableData.value = payload.data?.data || []
    total.value = payload.data?.totalCount || 0
    
    // 🔧 修复：如果实时更新已开启，发送查询请求
    if (connectionStatus.value === 'Connected') {
      await sendRealTimeQuery()
    }
  } catch (err: any) {
    console.error('获取列表失败:', err)
    ElMessage.error(err?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

const sumIn = computed(() => tableData.value.reduce((s, x) => s + (Number(x.inQuantity) || 0), 0))
const sumOut = computed(() => tableData.value.reduce((s, x) => s + (Number(x.outQuantity) || 0), 0))
const sumBalance = computed(() => tableData.value.reduce((s, x) => s + (Number(x.balanceQuantity) || 0), 0))

function formatNumber(n: number | string) {
  const num = Number(n ?? 0)
  return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(num)
}

function exportCsv() {
  if (!tableData.value.length) return
  const headers = ['产品名称','产品编号','规格型号','单位','仓库','单价','申请人','入库数','出库数','结存数']
  const rows = tableData.value.map(r => [
    r.productName, r.productNumber, r.specification, r.unit,
    r.warehouseName, r.unitPrice, r.applicant, r.inQuantity,
    r.outQuantity, r.balanceQuantity
  ])
  const csv = [headers, ...rows].map(row => row.map(cell => `"${String(cell ?? '').replace(/"/g,'""')}"`).join(',')).join('\n')
  const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `报表汇总_${Date.now()}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

function handleSearch() {
  query.pageindex = 1
  fetchList()
}

function handleReset() {
  query.ProductName = ''
  query.pageindex = 1
  query.pagesize = 10
  fetchList()
}

function handleCurrentChange(page: number) {
  query.pageindex = page
  fetchList()
}

function handleSizeChange(size: number) {
  query.pagesize = size
  query.pageindex = 1
  fetchList()
}

// 🔧 修复：组件挂载时的处理
onMounted(async () => {
  console.log('组件挂载，开始初始化...')
  await fetchList()
  // 🔧 修改：页面加载时自动开启实时连接
  await initSignalR()
})

// 🔧 修复：组件卸载时的清理
onUnmounted(async () => {
  if (connection.value) {
    await connection.value.stop()
    connection.value = null
  }
})

const detailVisible = ref(false)
const detailRow = ref<SupplierItem | null>(null)
const router = useRouter()
function openDetail(row: SupplierItem){
  try {
    router.push({ name: 'InboundandOutboundDetails', query: { productName: row.productName } })
  } catch (error) {
    console.error('导航失败:', error)
    ElMessage.error('页面跳转失败')
  }
}
</script>

<style scoped>
.page-wrap{ display:flex; flex-direction:column; gap:12px; }
.page-header{ display:flex; align-items:center; justify-content:space-between; }
.page-title{ font-size:18px; font-weight:600; display:flex; align-items:center; gap:8px; }
.title-tag{ vertical-align: middle; }
.status-tag{ vertical-align: middle; }
.page-actions{ display:flex; gap:8px; }
.stats-row{ display:grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap:12px; }
.stat-card{ text-align:center; }
.stat-title{ color:#6b7280; font-size:12px; }
.stat-value{ font-size:20px; font-weight:700; margin-top:4px; }
.pager{ display:flex; justify-content:flex-end; margin-top:12px; }
.update-alert, .connection-alert, .error-alert{ margin-bottom:12px; }
</style>